package com.example.ui.contact.chat;


import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.NetContact;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;



public class SendMsgAsyncTask {
	private String content;
	private String fromid;
	private String toid;
	private Handler mHandler;
	private MyAsyncTask mTask;
	private String mUserId;//周围人列表中的userid
	private OnSendScuessListener mListener;

	public interface OnSendScuessListener {
		void sendScuess();
	}

	public void setOnSendScuessListener(OnSendScuessListener listener) {
		this.mListener = listener;
	}

	Runnable reSend = new Runnable() {

		@Override
		public void run() {
			L.i("重发  resend msg...");
			send();//重发
		}
	};

	
	public SendMsgAsyncTask(String content,String fromid,String toid) {

		this.content = content;
		this.fromid = fromid;
		this.toid = toid;
		mHandler = new Handler();
	}
	// 发送
	public void send() {
		if (NetUtil.isNetConnected(HSApplication.getInstance())) {//如果网络可用
			mTask = new MyAsyncTask();
			mTask.execute();
		} else {
			T.showLong(HSApplication.getInstance(), R.string.net_error_tip);
		}
	}

	// 停止
	public void stop() {
		if (mTask != null)
			mTask.cancel(true);
	}
	
	class MyAsyncTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... message) {
			String result = "200";
			
			SendMsg(NetContact.SEND_MSG_URL,content,fromid,toid);

			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			L.i("send msg result:"+result);
			if (!result.contains("200")) {// 如果消息发送失败，则100ms后重发
				mHandler.postDelayed(reSend, 100);
			} else {
				if (mListener != null)
					mListener.sendScuess();
			}
		}
	}
	
    private static AsyncHttpClient client = new AsyncHttpClient();
	public void SendMsg(String url,String content,String fromid,String toid){

    	RequestParams params = new RequestParams();
    	params.put("fromid", fromid);
    	params.put("toid", toid);
    	params.put("content", content);
    	System.out.println("params="+params.toString());
    	client.post(url, params,new AsyncHttpResponseHandler(){
    		@Override
    		public void onSuccess(String response) {
    			L.Debug("chat send response", response);
    		}
    	});

	}
}
